package com.hxzy.util;

import java.util.List;

/**
 * @author nick
 */
public class PageUtil<T> { //T，泛型，从数据库查询的数据的对象

    public static final int DEFAULT_PAGE_INDEX = 1;//默认显示第一页
    public static final int DEFAULT_PAGE_SIZE = 5; //默认显示5条数据

    public PageUtil() {

    }

    public PageUtil(int pageIndex) {
        this.pageIndex = pageIndex;
    }

    public PageUtil(int pageIndex, int pageSize) {
        this.pageIndex = pageIndex;
        this.pageSize = pageSize;
    }

    public PageUtil(int totals, List<T> data) {
        this.totals = totals;
        this.data = data;
    }

    public PageUtil(int pageIndex, int pageSize, int totals, List<T> data) {
        this.pageIndex = pageIndex;
        this.pageSize = pageSize;
        this.totals = totals;
        this.data = data;

        this.pages = this.getPages();
    }

    private int pageIndex = DEFAULT_PAGE_INDEX; //当前页码
    private int pageSize = DEFAULT_PAGE_SIZE; //每页显示的数据的条数
    private int totals; //总共有多少条数据，需要向数据库查询
    private int pages; //总共有多少页
    private List<T> data;

    public int getPageIndex() {
        return pageIndex;
    }

    public void setPageIndex(int pageIndex) {
        this.pageIndex = pageIndex;
    }

    public int getPageSize() {
        return pageSize;
    }

    public void setPageSize(int pageSize) {
        this.pageSize = pageSize;
    }

    public int getTotals() {
        return totals;
    }

    public void setTotals(int totals) {
        this.totals = totals;
        this.pages = this.getPages();
    }

    public List<T> getData() {
        return data;
    }

    public void setData(List<T> data) {
        this.data = data;
    }

    /**
     * 计算总共有多少页
     * @return
     */
    public int getPages() {
        int pages = this.totals / this.pageSize;
        return this.totals % this.pageSize == 0 ? pages : pages + 1;
    }

    /**
     * 返回上一页的页码
     * @return
     */
    public int prevPage(){
        if (this.pageIndex > 1) { //如果当前页码大于1，
            return this.pageIndex - 1;
        }
        return 1;
    }

    /**
     * 返回下一页的页码
     * @return
     */
    public int nextPage(){
        if (this.pageIndex < this.getPages()) { //如果当前页小于总共页码
            return this.pageIndex + 1;
        }
        return this.pages;
    }

    /**
     * 判断是否有上一页
     * @return
     */
    public boolean hasPrev(){
        int prevPage = this.prevPage();
        if (prevPage < this.pageIndex) {
            return true;
        }
        return false;
    }

    /**
     * 判断是否有下一页
     * @return
     */
    public boolean hasNext(){
        int nextPage = this.nextPage();
        return this.pageIndex < nextPage;
    }
}
